
/***********************
 * 地图管理页面逻辑代码
 ***********************/
$(function () {
    function map() {
        let _map, _styleEditor;
        let _initLatlng = [30.595188, 114.299625];
        let _layers = [
            {
                name: '天地图矢量底图',
                img: 'images/vec_c.png',
                code: 'tdt_vec_c',
                added: true
            },
            {
                name: '天地图矢量注记',
                img: 'images/cva_c.png',
                code: 'tdt_cva_c',
                added: true
            },
            {
                name: '天地图影像底图',
                img: 'images/img_c.png',
                code: 'tdt_img_c',
                added: false
            },
            {
                name: '天地图影像注记',
                img: 'images/cia_c.png',
                code: 'tdt_cia_c',
                added: false
            }
        ]

        //Geoserver参数
        let _gsConfig = {
            url: '',
            workspace: '',
            user: '',
            password: ''
        }

        //Postgis参数
        let _pgConfig = {
            name: '',
            host: '',
            port: '',
            db: '',
            user: '',
            password: ''
        }

        function init() {
            //避免修改参数之后参数变化
            for (const key in _gsConfig) {
                loadGeoserverConfig(key);
            }
            for (const key in _pgConfig) {
                loadPostGISConfig(key);
            }
        }

        /**
         * 初始化UI，特别是相关事件
         */
        function initUI() {
            _map = L.map('map_container', {
                attributionControl: false
            }).setView(_initLatlng, 12);

            $(window).on('resize', function () {
                _map.invalidateSize();
            })

            addLayers();

            //图层列表展示隐藏
            $('.layer-title .close').on('click', function () {
                $('.layer-container').fadeOut();
            });

            $('.leaflet-control-layer').on('click', function () {
                $('.layer-container').fadeIn();
            });

            $('#btn_add_layer').on('click', function () {
                $('#modal_layer_select').modal();
            });

            //图层选择窗口弹出时的事件
            $('#modal_layer_select').on('show.bs.modal', function (event) {
                loadLayerSelector();
            });

            $('#btn_layer_select').on('click', function () {
                _layers.forEach(layer => {
                    layer.added = false;
                });
                var checkElements = $('#layer_select_container .active').toArray();
                checkElements.forEach(element => {
                    var code = element.id.replace('layer_sel_', '');
                    _layers.forEach(layer => {
                        if (layer.code == code) {
                            layer.added = true;
                        }
                    });
                });
                addLayers();
                $('#modal_layer_select').modal('hide');
            });
        }

        /**
         * 加载geoserver参数
         * @param {*} key 
         */
        function loadGeoserverConfig(key) {
            var requestKey = 'geoserver_' + key;
            $.get(`${Config.BASE_URL}/api/configuration/${requestKey}`, function (response) {
                if (response.succeeded && response.data) {
                    _gsConfig[key] = response.data.value;
                }
            });
        }

        /**
        * 加载PostGIS参数
        * @param {*} key 
        */
        function loadPostGISConfig(key) {
            var requestKey = 'postgis_' + key;
            $.get(`${Config.BASE_URL}/api/configuration/${requestKey}`, function (response) {
                if (response.succeeded && response.data) {
                    _pgConfig[key] = response.data.value;
                }
            });
        }

        /**
         * 加载图层选择器
         */
        function loadLayerSelector() {
            $('#layer_select_container').empty();
            _layers.forEach(layer => {
                let html = `
                <div class="col-3">
                    <div id="layer_sel_${layer.code}" class="card card-figure ${layer.added ? 'active' : ''}">
                        <figure class="figure">
                            <div class="figure-img">
                                <img class="img-full" src="${layer.img}" alt="${layer.name}">
                                <a href="#" class="img-link">
                                    <div class="tile tile-circle ">
                                        <span><i class="bi bi-check-circle-fill"></i></span>
                                    </div>
                                </a>
                            </div>
                            <figcaption class="figure-caption">
                                <h6 class="figure-title"><a href="#">${layer.name}</a></h6>
                            </figcaption>
                        </figure>
                    </div>
                </div>
                `
                $('#layer_select_container').append(html);
            });

            var uploadhtml = `
            <div class="col-3">
                <div id="layer_sel_upload" class="card card-figure">
                    <figure class="figure">
                        <div class="figure-img">
                            <input id="input_layer_upload" accept="application/zip,application/json" type="file" name="file">
                            <a href="javascript:void(0);" title="上传WGS84/CGS2000地理坐标系的geojson数据或shp数据的zip压缩包" class="img-link">
                                <div class="tile tile-circle ">
                                    <span><i class="bi bi-upload"></i></span>
                                </div>
                            </a>
                        </div>
                        <figcaption class="figure-caption">
                            <h6 class="figure-title">
                                <a title="上传WGS84/CGS2000地理坐标系的geojson数据或shp数据的zip压缩包" href="javascript:void(0);">上传数据</a>
                            </h6>
                        </figcaption>
                    </figure>
                </div>
            </div>
            `
            $('#layer_select_container').append(uploadhtml);

            $('.card-figure').on('click', function (e) {
                if (this.id == 'layer_sel_upload') {
                    //上传
                    $('#input_layer_upload').trigger('click');
                }
                else {
                    //勾选
                    if ($(this).hasClass('active')) {
                        $(this).removeClass('active');
                    }
                    else {
                        $(this).addClass('active');
                    }
                }
            });

            //避免传递到上层
            $('#input_layer_upload').on('click', function (event) {
                event.stopPropagation();
            });

            //上传数据
            $('#input_layer_upload').on('change', function (event) {
                var file = event.target.files[0];
                var layerName = file.name.substring(0, file.name.lastIndexOf('.'));
                //具有同名图层则不处理
                for (let index = 0; index < _layers.length; index++) {
                    const code = _layers[index].code;
                    if (code.replace('geojson_','').replace('gswms_','') == layerName) {
                        $.notifyErrors('地图库中存在同名的图层');
                        return;
                    }
                    
                }
                if (file.name.toLowerCase().endsWith('.json') || file.name.toLowerCase().endsWith('.geojson')) {
                    let reader = new FileReader();
                    reader.onload = (e) => {
                        let geojson = JSON.parse(reader.result);
                        if (!geojson.features || geojson.features.length < 0) {
                            $.notifyErrors('GeoJson中没有要素');
                            return;
                        }
                        let geometryType = geojson.features[0].geometry.type;
                        for (let index = 0; index < geojson.features.length; index++) {
                            if (geojson.features[index].geometry.type != geometryType) {
                                $.notifyErrors('GeoJson中包含多重几何类型的数据，无法配置样式和发布服务');
                                return;
                            }
                        }
                        _layers.push({
                            name: '临时_' + layerName,
                            img: 'images/template.png',
                            code: 'geojson_' + layerName,
                            added: true,
                            data: geojson
                        })
                        loadLayerSelector();
                    }
                    reader.readAsText(file);

                }
                else if (file.name.toLowerCase().endsWith('.zip')) {
                    //处理压缩包，读取shp和dbf成Arraybuffer
                    JSZip.loadAsync(file).then(function (zip) {
                        let shpData, dbfData;
                        zip.forEach((relativePath, zipEntry) => {
                            if (relativePath.toLowerCase().endsWith('.shp')) {
                                zip.file(relativePath).async("arraybuffer").then(data => {
                                    shpData = data;
                                    if (shpData && dbfData) {
                                        readShp(shpData, dbfData, layerName);
                                    }
                                })
                            }
                            else if (relativePath.toLowerCase().endsWith('.dbf')) {
                                zip.file(relativePath).async("arraybuffer").then(data => {
                                    dbfData = data;
                                    if (shpData && dbfData) {
                                        readShp(shpData, dbfData, layerName);
                                    }
                                })
                            }
                        });
                    })
                }
                else {
                    $.notifyErrors('选择的文件类型不正确');
                }
            })
        }

        /**
         * 读取shp数据
         * @param {*} shpData 
         * @param {*} dbfData 
         * @param {*} name 
         */
        function readShp(shpData, dbfData, name) {
            shapefile.read(shpData, dbfData, { encoding: "utf8" }).then(features => {
                _layers.push({
                    name: '临时_' + name,
                    img: 'images/template.png',
                    code: 'geojson_' + name,
                    added: true,
                    data: features
                })
                loadLayerSelector();
            })
        }

        /**
         * 加载地图图层
         */
        function addLayers() {
            const tdtOption = {
                key: '304bc664f193742e0ad7ad3b77d5dccd'
            }

            _layers.forEach(layer => {
                if (layer.added) {
                    if (!layer.layerInstance) {
                        if (layer.code == 'tdt_vec_c') {
                            layer.layerInstance = L.tileLayer.chinaProvider('TianDiTu.Normal.Map', tdtOption);
                        }
                        else if (layer.code == 'tdt_cva_c') {
                            layer.layerInstance = L.tileLayer.chinaProvider('TianDiTu.Normal.Annotion', tdtOption);
                        }
                        else if (layer.code == 'tdt_img_c') {
                            layer.layerInstance = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map', tdtOption);
                        }
                        else if (layer.code == 'tdt_cia_c') {
                            layer.layerInstance = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion', tdtOption);
                        }
                        else if (layer.code.startsWith('geojson_')) {
                            layer.layerInstance = L.geoJSON(layer.data, {
                                pointToLayer: function (geoJsonPoint, latlng) {
                                    return L.circleMarker(latlng, { radius: 5 })
                                }
                            });
                            for (const key in layer.layerInstance._layers) {
                                layer.layerInstance.options = layer.layerInstance._layers[key].options;
                                break;
                            }
                        }
                        else if (layer.code.startsWith('gswms_')) {
                            layer.layerInstance = L.Geoserver.wms(`${_gsConfig.url}/wms`, {
                                layers: `${_gsConfig.workspace}:${layer.name}`,
                            });
                        }
                        layer.layerInstance.code = layer.code;
                    }
                    if (!_map.hasLayer(layer.layerInstance)) {
                        addLayer(layer.layerInstance, layer.name,layer.code);
                    }
                }
                else {
                    if (layer.layerInstance && _map.hasLayer(layer.layerInstance)) {
                        removeLayer(layer.layerInstance)
                    }
                }
            });
        }

        /**
         * 添加图层
         * @param {*} layer 
         */
        function addLayer(layer, name,code) {
            _map.addLayer(layer);
            let id = 'layer_' + layer._leaflet_id;
            let opBtns = '';
            if (code.startsWith('geojson_')) {
                opBtns = `
                <a title="设置样式" class='layer-option' id="layer_style_${id}"><i class="bi bi-palette"></i></a>
                <a title="发布图层" class='layer-option' id="layer_store_${id}"><i class="bi bi-hdd-network-fill"></i></a>
                `;
            }
            else if (code.startsWith('gswms_')) {
                opBtns =`
                <a title="删除服务" class='layer-option' id="layer_delete_store_${id}"><i class="bi bi-dash-circle-fill"></i></a>
                `;
            }
            let html = `
            <div class="custom-control custom-checkbox">
                <input type="checkbox" checked class="custom-control-input" id="${id}">
                <label class="custom-control-label" for="${id}">${name}</label>
                <a title="删除图层" class='layer-option' id="layer_delete_${id}"><i class="bi bi-x-circle-fill"></i></a>
                ${opBtns}
            </div>
            `;
            $('.layer-list').prepend(html);

            let layerData;
            for (let index = 0; index < _layers.length; index++) {
                if (_layers[index].code == layer.code) {
                    layerData = _layers[index];
                    layerData.added = true;
                }
            }

            //可见选择框
            $('#' + id).on('change', function () {
                console.log(layer);
                if ($(this).prop('checked')) {
                    if (layer.setOpacity) {
                        layer.setOpacity(1);
                    }
                    else if (layer.setStyle) {
                        layer.setStyle({
                            opacity: layer.options.opacityPre || 1,
                            fillOpacity: layer.options.fillOpacityPre || 0.2
                        })
                    }
                }
                else {
                    if (layer.setOpacity) {
                        layer.setOpacity(0);
                    }
                    else if (layer.setStyle) {
                        if (layer.options.opacity != null) {
                            layer.options.opacityPre = layer.options.opacityPre
                        }
                        if (layer.options.fillOpacity != null) {
                            layer.options.fillOpacityPre = layer.options.fillOpacity
                        }
                        layer.setStyle({
                            opacity: 0,
                            fillOpacity: 0
                        })
                    }
                }
            })

            //删除按钮
            $('#layer_delete_' + id).on('click', function () {
                removeLayer(layer);
            });

            //删除服务按钮
            $('#layer_delete_store_' + id).on('click', function () {
                if (confirm('删除服务将删除GeoServer中的图层、相关样式和PostGIS中的数据，是否删除？')) {
                    let geoserver = new GeoServer(_gsConfig.url, _gsConfig.user, _gsConfig.password);
                    let geoname = layerData.code.replace('gswms_', '');
                    geoserver.deleteLayer(_gsConfig.workspace,geoname).then(lresult=>{
                        if (lresult) {
                            geoserver.deleteStyle(_gsConfig.workspace,'style_' + geoname).then(sresult=>{
                                if (sresult) {
                                    $.ajax({
                                        url: `${Config.BASE_URL}/api/geo-data/data/${geoname}`,
                                        method: 'DELETE',
                                        success: response => {
                                            if (response.succeeded) {
                                                $.notify('服务已删除', { type: 'success' });
                                                removeLayer(layerData.layerInstance);
                                                _layers.splice(_layers.indexOf(layerData),1);
                                            }
                                            else
                                            {
                                                $.notifyErrors(response.errors);
                                            }
                                        },
                                        error: error => {
                                            $.notifyErrors(error.responseText);
                                            reject();
                                        }
                                    });
                                }
                                else
                                {
                                    $.notifyErrors('样式删除失败');
                                }
                            })
                        }
                        else
                        {
                            $.notifyErrors('删除图层失败');
                        }
                    });
                }
            });

            //设置样式
            $('#layer_style_' + id).on('click', function () {
                $('.layer-container').fadeOut();
                if (!_styleEditor) {
                    _styleEditor = L.control.styleEditor({
                        strings: {
                            cancel: '取消',
                            cancelTitle: '取消样式编辑',
                            tooltip: '点击你想要编辑样式的要素',
                            tooltipNext: '关闭样式编辑'
                        },
                        useGrouping: true,
                    })
                    _map.addControl(_styleEditor);
                    _map.on('styleeditor:hidden', function (element) {
                        _styleEditor.disable();
                        $('.layer-container').fadeIn();
                    });
                }
                _map.addControl(_styleEditor);
                _styleEditor.enable(layer);
                //点击了才能编辑，蛮怪的
                for (const key in layer._layers) {
                    layer._layers[key].fire('click');
                    break;
                }
            })

            //发布图层
            $('#layer_store_' + id).on('click', function () {
                //暂时判断两个参数
                if (!_gsConfig.url || !_gsConfig.password) {
                    $.notifyErrors('没有配置GeoServer参数');
                    return;
                }

                let geoserver = new GeoServer(_gsConfig.url, _gsConfig.user, _gsConfig.password);
                //在geoserver中创建工作空间和数据存储
                geoserver.getWorkspaces().then(response=>{
                    let workspace = response.workspaces.workspace;
                    //有工作空间就不管
                    if (workspace) {
                        for (let index = 0; index < workspace.length; index++) {
                            if (workspace[index].name == _gsConfig.workspace) {
                                //处理数据存储
                                createDatastore();
                                return;
                            }
                        }
                    }
                    geoserver.createWorkspace(_gsConfig.workspace).then(data=>{
                        //处理数据存储
                        createDatastore();
                    });
                })
                //上传数据
                let geodata = layerData.data;
                let geoname = layerData.code.replace('geojson_', '');
                if (geodata) {
                    var data = {
                        name:geoname,
                        geojson:JSON.stringify(geodata)
                    }
                    checkLayer(geoserver,geoname).then(lr=>{
                        checkDb(geoname).then(dr=>{
                            checkStyle(geoserver,'style_' + geoname).then(sr=>{
                                $.post(`${Config.BASE_URL}/api/geo-data/store`,JSON.stringify(data),function(response){
                                    if (response.succeeded) {
                                        //创建样式
                                        createStyle(geoserver, geoname, layerData.data.features[0].geometry.type, layer.options).then(sdata=>{
                                             //发布服务
                                            geoserver.publishLayer(_gsConfig.workspace,_pgConfig.name,geoname,response.data).then(ldata=>{
                                                //设置样式
                                                geoserver.setStyle(_gsConfig.workspace,geoname,'style_' + geoname).then(ssdata=>{
                                                    $.notify('图层发布成功', { type: 'success' });
                                                    replaceTempLayer(geoname);
                                                    //TODO:保存地图图层信息
                                                }).catch(sserror=>{
                                                    $.notifyErrors(sserror.responseText);
                                                });
                                            }).catch(lerror=>{
                                                $.notifyErrors(lerror.responseText);
                                            });
                                        }).catch(serror=>{
                                            $.notifyErrors(serror.responseText);
                                        });
                                    }
                                    else
                                    {
                                        $.notifyErrors(response.errors);
                                    }
                                });
                            });
                        });
                    });
                }    
            })
        }

        /**
         * 检查地理数据库
         * @param {String} dataName 数据表名称
         * @returns 
         */
        function checkDb(dataName)
        {
            return new Promise(function(resolve,reject){
                $.get(`${Config.BASE_URL}/api/geo-data/exist/${dataName}`,function(existResponse){
                    if (existResponse.data) {
                        if (confirm('空间数据库中存在表' + dataName + '，是否删除？')) {
                            $.ajax({
                                url: `${Config.BASE_URL}/api/geo-data/data/${dataName}`,
                                method: 'DELETE',
                                success: response => {
                                    if (response.succeeded) {
                                        resolve();
                                    }
                                    else
                                    {
                                        $.notifyErrors(response.errors);
                                        reject();
                                    }
                                },
                                error: error => {
                                    $.notifyErrors(error.responseText);
                                    reject();
                                }
                            });
                        }
                        else
                        {
                            reject();
                        }
                    }
                    else
                    {
                        resolve();
                    }
                })
            })
        }

        /**
         * 检查GeoServer样式
         * @param {GeoServer} geoserver geoserver实例
         * @param {String} styleName 样式名称
         * @returns 
         */
        function checkStyle(geoserver,styleName)
        {
            return new Promise(function(resolve,reject){
                geoserver.styleExist(_gsConfig.workspace,styleName).then(exist=>{
                    if (exist) {
                        if (confirm('GeoServer中存在样式' + styleName + '，是否删除？')) {
                            geoserver.deleteStyle(_gsConfig.workspace,styleName).then(deleted=>{
                                if (deleted) {
                                    resolve();
                                }
                                else
                                {
                                    $.notifyErrors("删除样式失败");
                                    reject();
                                }
                            })
                        }
                        else
                        {
                            reject();
                        }
                    }
                    else
                    {
                        resolve(true);
                    }
                })
            })
        }

        /**
         * 检查GeoServer图层
         * @param {GeoServer} geoserver geoserver实例
         * @param {String} layerName 图层名称
         * @returns 
         */
         function checkLayer(geoserver,layerName)
         {
             return new Promise(function(resolve,reject){
                 geoserver.layerExist(_gsConfig.workspace,layerName).then(exist=>{
                     if (exist) {
                         if (confirm('GeoServer中存在图层' + layerName + '，是否删除？')) {
                             geoserver.deleteLayer(_gsConfig.workspace,layerName).then(deleted=>{
                                 if (deleted) {
                                     resolve();
                                 }
                                 else
                                 {
                                     $.notifyErrors("删除图层失败");
                                     reject();
                                 }
                             })
                         }
                         else
                         {
                            reject();
                         }
                     }
                     else
                     {
                         resolve();
                     }
                 })
             })
         }

        /**
         * 创建数据存储
         */
        function createDatastore() {
            let geoserver = new GeoServer(_gsConfig.url, _gsConfig.user, _gsConfig.password);
            geoserver.getDatastores(_gsConfig.workspace).then(response => {
                let datastore = response.dataStores.dataStore;
                if (datastore) {
                    for (let index = 0; index < datastore.length; index++) {
                        if (datastore[index].name == _pgConfig.name) {
                            return
                        }
                    }
                }
                geoserver.createPGDatastore(_gsConfig.workspace, _pgConfig.name, _pgConfig.host, _pgConfig.port, _pgConfig.db, _pgConfig.user, _pgConfig.password);
            })
        }

        /**
         * 创建样式
         * @param {Geoserver} geoserver GeoServer实例
         * @param {*} name 数据名称
         * @param {*} geometryType 数据几何类型
         * @param {*} params 样式参数
         */
        function createStyle(geoserver, name, geometryType, params) {
            let style = '';
            var dash = '';
            if (params.dashArray && params.dashArray != 1) {
                dash = `<sld:CssParameter name="stroke-dasharray">${params.dashArray ? params.dashArray.replaceAll(',','') : 1}</sld:CssParameter>`
            }
            switch (geometryType) {
                case 'Point':
                    style = `<?xml version="1.0" encoding="UTF-8"?>
                    <sld:StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0">
                    <sld:NamedLayer>
                        <sld:Name>style_${name}</sld:Name>
                        <sld:UserStyle>
                            <sld:Name>style_${name}</sld:Name>
                            <sld:Title>真和民平台生成样式：${name}</sld:Title>
                            <sld:FeatureTypeStyle>
                                <sld:Name>Point</sld:Name>
                                <sld:Rule>
                                    <sld:PointSymbolizer>
                                        <sld:Graphic>
                                        <sld:Mark>
                                            <sld:WellKnownName>circle</sld:WellKnownName>
                                            <sld:Fill>
                                                <sld:CssParameter name="fill">${params.fillColor || params.color}</sld:CssParameter>
                                                <sld:CssParameter name="fill-opacity">${params.fillOpacity}</sld:CssParameter>
                                            </sld:Fill>
                                            <sld:Stroke>
                                                <sld:CssParameter name="stroke">${params.color}</sld:CssParameter>
                                                <sld:CssParameter name="stroke-width">${params.weight}</sld:CssParameter>
                                                <sld:CssParameter name="stroke-opacity">${params.opacity}</sld:CssParameter>
                                                ${dash}
                                            </sld:Stroke>
                                        </sld:Mark>
                                        <sld:Size>${params.radius}</sld:Size>
                                        </sld:Graphic>
                                    </sld:PointSymbolizer>
                                </sld:Rule>
                            </sld:FeatureTypeStyle>
                        </sld:UserStyle>
                    </sld:NamedLayer>
                    </sld:StyledLayerDescriptor>`
                    break;
                case 'LineString':
                case 'MultiLineString ':
                    style = `<?xml version="1.0" encoding="UTF-8"?>
                    <sld:StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0">
                    <sld:NamedLayer>
                        <sld:Name>style_${name}</sld:Name>
                        <sld:UserStyle>
                            <sld:Name>style_${name}</sld:Name>
                            <sld:Title>真和民平台生成样式：${name}</sld:Title>
                            <sld:FeatureTypeStyle>
                                <sld:Name>LineString</sld:Name>
                                <sld:Rule>
                                    <sld:LineSymbolizer>
                                        <sld:Stroke>
                                            <sld:CssParameter name="stroke">${params.color}</sld:CssParameter>
                                            <sld:CssParameter name="stroke-width">${params.weight}</sld:CssParameter>
                                            <sld:CssParameter name="stroke-opacity">${params.opacity}</sld:CssParameter>
                                            ${dash}
                                        </sld:Stroke>
                                    </sld:LineSymbolizer>
                                </sld:Rule>
                            </sld:FeatureTypeStyle>
                        </sld:UserStyle>
                    </sld:NamedLayer>
                    </sld:StyledLayerDescriptor>`
                    break;
                case 'Polygon':
                case 'MultiPolygon':
                    style = `<?xml version="1.0" encoding="UTF-8"?>
                    <sld:StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc" version="1.0.0">
                        <sld:NamedLayer>
                            <sld:Name>style_${name}</sld:Name>
                            <sld:UserStyle>
                                <sld:Name>style_${name}</sld:Name>
                                <sld:Title>真和民平台生成样式：${name}</sld:Title>
                                <sld:FeatureTypeStyle>
                                    <sld:Name>Polygon</sld:Name>
                                    <sld:Rule>
                                        <sld:PolygonSymbolizer>
                                            <sld:Fill>
                                                <sld:CssParameter name="fill">${params.fillColor || params.color}</sld:CssParameter>
                                                <sld:CssParameter name="fill-opacity">${params.fillOpacity}</sld:CssParameter>
                                            </sld:Fill>
                                            <sld:Stroke>
                                                <sld:CssParameter name="stroke">${params.color}</sld:CssParameter>
                                                <sld:CssParameter name="stroke-width">${params.weight}</sld:CssParameter>
                                                <sld:CssParameter name="stroke-opacity">${params.opacity}</sld:CssParameter>
                                                ${dash}
                                            </sld:Stroke>
                                        </sld:PolygonSymbolizer>
                                    </sld:Rule>
                                </sld:FeatureTypeStyle>
                            </sld:UserStyle>
                        </sld:NamedLayer>
                    </sld:StyledLayerDescriptor>`
                    break;
                default:
                    break;
            }
            return geoserver.createStyle(_gsConfig.workspace,style);
        }

        /**
         * 发布之后将临时数据替换成发布的数据
         * @param {*} geoname 
         */
        function replaceTempLayer(geoname)
        {
            for (let index = 0; index < _layers.length; index++) {
                const layerData = _layers[index];
                if (layerData.name == '临时_' + geoname && layerData.code == 'geojson_' + geoname) {
                    removeLayer(layerData.layerInstance);
                    _layers.splice(index,1);
                    break;
                }
            }
            let gslayerData = {
                name:  geoname,
                img: 'images/map.png',
                code: 'gswms_' + geoname,
                added: true
            };
            _layers.push(gslayerData);
            addLayers();
        }

        /**
         * 删除图层
         * @param {*} layer 
         */
        function removeLayer(layer) {
            if (_map.hasLayer) {
                let id = 'layer_' + layer._leaflet_id;
                $($('#' + id)[0].parentElement).remove();
                _layers.forEach(alayer => {
                    if (alayer.code == layer.code) {
                        alayer.added = false;
                    }
                });
                _map.removeLayer(layer);
            }
        }

        return {
            init: init,
            initUI: initUI
        }
    }


    window.MainMap = map();
    MainMap.initUI();
})